<template>
  <div class="param-main">
    <el-form
      ref="tblMain"
      :model="serachForm"
      labelPosition="right"
      inline=""
      label-suffix=":"
      label-width="110px"
    >
      <div class="page-pane2">
        <el-button size="small" @click="dataSave()">保存</el-button>
      </div>
    </el-form>
    <div style="height: calc(100% - 60px)">
      <vxe-table
        border
        show-overflow
        resizable
        keep-source
        ref="xTree"
        row-id="id"
        :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
        :tree-config="{
          transform: true,
          lazy: true,
          hasChild: 'hasChild',
          loadMethod: loadChildrenMethod
        }"
        :data="listData"
        style="height: 100%;overflow: auto;"
      >
        <vxe-column
          field="name"
          title="区域名称"
          width="260"
          tree-node
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input v-model="row.name" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column
          field="type"
          title="区域类型"
          :edit-render="{}"
          :filters="typeDataList"
          :filter-multiple="false"
          :formatter="formatterType"
        >
          <template #edit="{ row }">
            <vxe-select v-model="row.type" placeholder="默认尺寸" :disabled="saveType=='add'">
              <vxe-option
                v-for="item in typeDataList"
                :key="item.code"
                :value="item.code"
                :label="item.value"
              ></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column title="操作" >
          <template #default="{ row }">
            <vxe-button
              type="text"
              status="primary"
              v-if="row.type != 'street'"
              @click="insertRow(row, 'top')"
              >新增</vxe-button
            >
            <vxe-button type="text" status="danger" @click="removeRow(row)"
              >删除</vxe-button
            >
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>
<script>
import {
  addSysRegion,
  delSysRegion,
  upSysRegion,
  getSysRegionList,
} from '@/api/carLine'

export default {
  name: 'applyMain',
  props: ['pageData'],
  data() {
    return {
      rowData: {},
      title: '',
      levelList: [],
      loading: false,
      listData: [],
      selection: [],
      serachForm: {
        code: '',
        type: 'province'
      },
      pageInfo: {
        page: 1,
        size: 100,
        total: 0
      },
      brands: [],
      tableData: [],
      typeList: ['province', 'city', 'area', 'street'],
      typeDataList: [
        {
          code: 'province',
          value: '省级'
        },
        {
          code: 'city',
          value: '城市'
        },
        {
          code: 'area',
          value: '区县'
        },
        {
          code: 'street',
          value: '乡镇/街道'
        }
      ],
      saveType: 'update'
    }
  },
  watch: {
    pageData() {
      this.initTableData()
    }
  },
  created() {
    let data = this.$route.query.data
      ? this.$route.query.data
      : {
          initial: '',
          name: '所有品牌',
          path: '/ope/apply'
        } //考评申请id
    this.levelList.push(data)
  },
  mounted() {
    this.initTableData()
  },
  methods: {
    formatterType({ cellValue }) {
      let item = this.typeDataList.find((item) => item.code === cellValue)
      return item ? item.value : ''
    },
    loadChildrenMethod({ row }) {
      this.serachForm.code = row.code
      let index = this.typeList.indexOf(row.type)
      this.serachForm.type = this.typeList[index + 1]
      // 异步加载子节点
      return new Promise((resolve) => {
        setTimeout(() => {
          this.initTableData().then((childs) => {
            resolve(childs)
          })
        }, 500)
      })
    },
    async insertRow(currRow, locat) {
      this.saveType = 'add'
      const $table = this.$refs.xTree
      // 如果 null 则插入到目标节点顶部
      // 如果 -1 则插入到目标节点底部
      // 如果 row 则有插入到效的目标节点该行的位置
      const rid = Date.now()
      if (locat === 'top') {
         let index = this.typeList.indexOf(currRow.type)
         const record = {
          name: `新数据${rid}`,
          id: rid,
          areaCode: currRow.areaCode ? currRow.areaCode : null,
          cityCode: currRow.cityCode ? currRow.cityCode : null,
          provinceCode: currRow.code ? currRow.code : null,
          parentId: currRow.id,
          streetCode: currRow.streetCode ? currRow.streetCode : null,
          type: this.typeList[index + 1]
        }
        const { row: newRow } = await $table.insert(record)
        await $table.setTreeExpand(currRow, true) // 将父节点展开
        await $table.setActiveRow(newRow) // 插入子节点
      }
    },
    async removeRow(row) {
      this.saveType = 'remove'
      const $table = this.$refs.xTree
      const removeRecords = $table.getRemoveRecords();
      this.deleteEvent(removeRecords)
      await $table.remove(row)
    },
    dataSave() {
      const $table = this.$refs.xTree
      if (this.saveType == 'add') {
        const insertRecords = $table.getInsertRecords()
        this.saveData(insertRecords,'add')
      } else if (this.saveType == 'update') {
        const updateRecords = $table.getUpdateRecords()
        this.saveData(updateRecords,'update')
      }
    },
    saveData(val,type) {
      if (type == 'add') {
        val.forEach(el => {
          addSysRegion(el).then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.initTableData()
            } else {
              this.$message({
                type: 'error',
                message: '操作失败!'
              })
            }
          })
        });
      } else {
         val.forEach(el => {
          upSysRegion(el).then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.initTableData()
            } else {
              this.$message({
                type: 'error',
                message: '操作失败!'
              })
            }
          })
        })
      }
    },
    initTableData() {
      let me = this
      me.selection = []
      let param = {
        page: me.pageInfo.page,
        size: me.pageInfo.size,
        ...me.serachForm
      }
      me.loading = true
      return new Promise((resolve) => {
        getSysRegionList(param)
          .then((res) => {
            me.loading = false
            const { code = undefined, data = {} } = res.data
            if (!code) {
              if (me.serachForm.type != 'street') {
                data.content.map((item) => {
                  item.hasChild = true
                })
              }
              if (me.serachForm.type == 'province') {
                me.listData = data.content
              } else {
                resolve(data.content)
              }
            }else{
              me.$message.error(data)
            }
          })
          .catch(() => {
            me.$message.error('服务器繁忙')
            me.loading = false
          })
      })
    },
    deleteEvent(val) {
      this.$confirm('此操作将永久删除该区域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let ids = val.map((item) => {
            return item.id
          })
          delSysRegion(ids).then((res) => {
            const { code = undefined, data = {} } = res.data
            if (!code) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.initTableData()
            } else {
              this.$message({
                type: 'error',
                message: '操作失败!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
